import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/base_state.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/bean/user.dart';
import 'package:yuan_hang_app/http/api.dart';
import 'package:yuan_hang_app/http/http_utils.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_constant.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/common_utils.dart';
import 'package:yuan_hang_app/utils/router_helper.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/views/home/view/activity/activity_detail_page.dart';
import 'package:yuan_hang_app/widget/custom_search.dart';
import 'package:yuan_hang_app/widget/common_dialog.dart';
import 'package:yuan_hang_app/widget/status_btn.dart';
import 'package:yuan_hang_app/widget/w_line.dart';
import 'package:yuan_hang_app/widget/w_list_view.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import 'package:yuan_hang_app/widget/w_toast.dart';

class MarketActivityPage extends StatefulWidget {
  const MarketActivityPage({super.key});

  @override
  BaseState<MarketActivityPage> createState() => _MarketActivityPageState();
}

class _MarketActivityPageState extends BaseState<MarketActivityPage> {
  List<Map> activityList = [];
  WListViewState? mCurrentStatus;
  int mPage = 1;
  String keyword = "";
  User userInfo = User.fromJson2();

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
      title: "活动查询",
      child: Column(
        children: [
          CustomSearch(
            showSort: false,
            hintText: "活动编号/活动名称",
            onTextChange: (text) {
              keyword = text;
              showLoading();
              mPage = 1;
              CommonUtils.antiShake(getActivityList);
            },
          ),
          Expanded(
              child: WListView(
            padding: EdgeInsets.symmetric(vertical: 10.px),
            itemBuilder: _activityItem,
            getDataList: (currentStatus, page) {
              mCurrentStatus = currentStatus;
              mPage = page;
              CommonUtils.antiShake(getActivityList);
            },
          ))
        ],
      ),
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    userInfo = WConstant().userInfo;
    setState(() {});
  }

  void getActivityList() {
    HttpUtils().get(Api.getMarketActivityList, queryParams: {
      "pageNum": mPage,
      "limit": 20,
      "keyword": keyword
    }).then((data) {
      hideLoading();

      ///  List<Map> list = data.data["records"] ?? [];
      print("===========================$mPage");
      if (data.resultCode == 200) {
        mCurrentStatus?.onRefreshData(data.data["records"] ?? [], mPage);
      } else {
        mCurrentStatus?.onFail(data.errMsg);
      }
    }).catchError((e) {
      hideLoading();
    });
  }

  Widget _activityItem(context, index, activityList) {
    Map item = activityList[index];
    item["modelName"] = getModelNames(item["modelIds"]);
    Map statusInfo = exchangeStatus(item["dateStatus"]);
    return GestureDetector(
      onTap: () {
        RouteHelper.pushWidget(
            context,
            ActivityDetailPage(
              activityId: item["id"],
              activityTypeName: item["activityTypeName"],
            ));
      },
      child: Container(
        margin: EdgeInsets.only(left: 15.px, right: 15.px, bottom: 10.px),
        padding: EdgeInsets.only(top: 10.px, bottom: 10.px, right: 10.px),
        decoration: BoxDecoration(
            color: WColors.white, borderRadius: BorderRadius.circular(10.px)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                WLine(
                  width: 4.px,
                  height: 16.px,
                  color: WColors.primaryColor,
                  marginRight: 10.px,
                ),
                Expanded(
                  child: WText(
                    StringUtils.safeGetValue(item["activityName"]),
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: WColors.mainTextColor,
                        fontSize: WDimens.tsLarge,
                        fontWeight: FontWeight.bold),
                  ),
                ),
                StatusBtn(
                  text: StringUtils.safeGetValue(statusInfo["title"]),
                  isItemBtn: true,
                  height: 28.px,
                  width: 60.px,
                  isTag: true,
                  color: statusInfo["color"],
                )
              ],
            ),
            Padding(
              padding: EdgeInsets.only(left: 10.px),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  WLine(
                    height: 0.5.px,
                    marginTop: 5.px,
                    marginBottom: 5.px,
                  ),
                  WText(
                    StringUtils.safeGetValue(item["modelName"],
                        placeHolder: "-"),
                    style: TextStyle(
                        color: WColors.mainTextColor,
                        fontSize: WDimens.tsMedium),
                  ),
                  SizedBox(
                    height: 5.px,
                  ),
                  Row(
                    children: [
                      WText(
                        "活动类型：",
                        textAlign: TextAlign.right,
                        style: TextStyle(
                          color: WColors.subTextColor,
                          fontSize: WDimens.tsMedium,
                        ),
                      ),
                      WText(
                        StringUtils.safeGetValue(item["activityTypeName"]),
                        textAlign: TextAlign.right,
                        style: TextStyle(
                          color: WColors.subTextColor,
                          fontSize: WDimens.tsMedium,
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: 5.px,
                  ),
                  WText(
                    "活动编号：${StringUtils.safeGetValue(item["activityCode"])}",
                    textAlign: TextAlign.right,
                    style: TextStyle(
                      color: WColors.subTextColor,
                      fontSize: WDimens.tsMedium,
                    ),
                  ),
                  SizedBox(
                    height: 5.px,
                  ),
                  Row(
                    children: [
                      WText(
                        "活动时间：",
                        textAlign: TextAlign.right,
                        style: TextStyle(
                          color: WColors.hintTextColor,
                          fontSize: WDimens.tsMedium,
                        ),
                      ),
                      WText(
                        StringUtils.safeGetValue(item["startDate"]),
                        textAlign: TextAlign.right,
                        style: TextStyle(
                          color: WColors.hintTextColor,
                          fontSize: WDimens.tsMedium,
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 5.px),
                        child: WText(
                          "-",
                          textAlign: TextAlign.right,
                          style: TextStyle(
                            color: WColors.hintTextColor,
                            fontSize: WDimens.tsMedium,
                          ),
                        ),
                      ),
                      WText(
                        StringUtils.safeGetValue(item["endDate"]),
                        textAlign: TextAlign.right,
                        style: TextStyle(
                          color: WColors.hintTextColor,
                          fontSize: WDimens.tsMedium,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            Offstage(
              offstage: item["dateStatus"] != 11141002,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  WLine(
                    height: 0.5.px,
                    marginTop: 5.px,
                    marginBottom: 5.px,
                    marginLeft: 10.px,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      StatusBtn(
                        height: 28.px,
                        isItemBtn: true,
                        text: "生成门店二维码",
                        color: WColors.primaryColor,
                        onPressed: () {
                          CommonDialog.showEWDialog(
                              context: context,
                              url: StringUtils.safeGetValue(item["shopQRUrl"]));
                        },
                      ),
                      SizedBox(
                        width: userInfo.roleCode == "DZ" ? 0 : 10.px,
                      ),
                      Offstage(
                        offstage: userInfo.roleCode == "DZ" ||
                            StringUtils.isEmpty2(item["personalQRUrl"]),
                        child: StatusBtn(
                          height: 28.px,
                          isItemBtn: true,
                          text: "生成个人二维码",
                          color: WColors.primaryColor,
                          onPressed: () {
                            CommonDialog.showEWDialog(
                                context: context,
                                url: StringUtils.safeGetValue(
                                    item["personalQRUrl"]));
                          },
                        ),
                      )
                    ],
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  String getModelNames(modelIds) {
    String name = "";
    List<String> ids = modelIds.toString().split(",");
    for (Map model in WConstant.modelList) {
      for (String id in ids) {
        if (model["id"].toString() == id) {
          name += model["label"] + ",";
          break;
        }
      }
    }
    if (name.isNotEmpty) {
      name = name.substring(0, name.length - 1);
    } else {
      name = "";
    }
    return name;
  }

  static Map exchangeStatus(status) {
    Map params = {"color": WColors.redMain, "title": "未开始"};

    if (status == 11141001) {
      params = {"color": WColors.redMain, "title": "未开始"};
    } else if (status == 11141002) {
      params = {"color": WColors.green, "title": "已开始"};
    } else if (status == 11141004) {
      params = {"color": WColors.hintTextColor, "title": "已结束"};
    }
    return params;
  }
}
